<?php

namespace App\Library\Service;


use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Str;

class WxMessageService
{
    //拍卖使用
    public static function auctionWxMess($goods = [], $user = [], $type = 1)
    {
        $msgContent = [];
        if ($type === 1) {//竞价成功提醒
            $msgContent = [
                'appid' => 'wx9eb0e71a0e599f0c',
                'template_id' => 'zPBgxe19CDqbhoQ6e1lCUQ3EiIhluZ4WOHrBwbfDRD0',
                'url' => '',
                'miniprogram' => '',
                'data' => [
                    'amount8' => ['value' => $goods->pay_price.'元'],
                    'time9' => ['value' => date('Y年m月d日 H:i'), time()],
                    'thing11' => ['value' => mb_substr($goods->title, 0, 10, 'utf-8')],
                ]
            ];
        }

        if ($type === 2) {//商品被拍(通知商家商品已拍)
            $msgContent = [
                'appid' => 'wx9eb0e71a0e599f0c',
                'template_id' => 'XxL1tqmWaS95VHdYWWJElCPd2NigN_qiO6Yw-hdDn0c',
                'url' => '',
                'miniprogram' => '',
                'data' => [
                    'time5' => ['value' => date('Y年m月d日 H:i', strtotime($goods['pay_at']))],
                    'thing6' => ['value' => mb_substr($goods['title'], 0, 10, 'utf-8')],
                    'character_string7' => ['value' => $goods['serial_number']],
                    'amount8' => ['value' => $goods['pay_price']],
                    'thing3' => ['value' => $user['address'] ?? '中国大陆！'],
                ]
            ];
        }

        if ($type === 3) {//下单失败通知
            $msgContent = [
                'appid' => 'wx9eb0e71a0e599f0c',
                'template_id' => 'pTPdlrQVrH2m0SUMiu3vsFlEo6-a5Jag44P2eUD3juQ',
                'url' => '',
                'miniprogram' => '',
                'data' => [
                    'thing2' => ['value' => $goods['title']],
                    'const5' => ['value' => '价格被超'],
                ]
            ];
        }

        if (!empty($user)) {
            file_put_contents('wxmess.txt', json_encode($msgContent));

            SELF::pushMsg(
                $user['openid'],
                $msgContent
            );
        }
        return true;
    }

    //普通商品使用
    public static function goodsWxMess($goods = [], $user = [], $seller = [], $type = 0)
    {
        $msgContent = [];
        if ($type === 1) {//新订单通知
            $msgContent = [
                'appid' => 'wx9eb0e71a0e599f0c',
                'template_id' => '-CnylRKJt2n6-ARcauGRcl1a1qvyimVzTmcjsHrArO0',
                'url' => '',
                'miniprogram' => '',
                'data' => [
                    'thing23' => ['value' => mb_substr($goods['product_name'], 0, 10, 'utf-8')],
                    'thing4' => ['value' => $goods['name']],
                    'phone_number10' => ['value' => $goods['mobile']],
                    'thing15' => ['value' => $goods['address']],
                    'time5' => ['value' => $goods['time']]
                ]
            ];
        }

        if ($type === 2) {//客户售后申请处理通知
            $msgContent = [
                'appid' => 'wx9eb0e71a0e599f0c',
                'template_id' => '0WF-jyoJz9b5NjeISvNCyq3C0GgfIhkSn06uKI1RchQ',
                'url' => '',
                'miniprogram' => '',
                'data' => [
                    'character_string1' => ['value' => $goods['goods_order_no']],
                    'character_string2' => ['value' => $goods['order_return_no']],
                    'thing3' => ['value' => mb_substr($goods['goods_name'], 0, 10, 'utf-8')],
                    'time4' => ['value' => $goods['time']],
                ]
            ];
        }

        if ($type === 3) {//发货通知
            $msgContent = [
                'appid' => 'wx9eb0e71a0e599f0c',
                'template_id' => 'FxLlmG4guKD5JYZ64F4Z1sZhEjj10FCpOkHFHxrf73k',
                'url' => '',
                'miniprogram' => '',
                'data' => [
                    'thing4' => ['value' => mb_substr($goods['goods_name'], 0, 10, 'utf-8')],
                    'time5' => ['value' => $goods['time']],
                    'character_string6' => ['value' => $goods['goods_order_no']],
                    'thing2' => ['value' => $goods['deliver_unit']],
                    'character_string13' => ['value' => $goods['logistics_no']],
                ]
            ];
        }

        if ($type === 4) {//售后订单申请处理通知
            $msgContent = [
                'appid' => 'wx9eb0e71a0e599f0c',
                'template_id' => 'l9aRtca0pV_h6C4EbGeM2sx4LJr1Xgg4tGqKFcJIZZ8',
                'url' => '',
                'miniprogram' => '',
                'data' => [
                    'character_string1' => ['value' => $goods['goods_order_no']],
                    'const2' => ['value' => $goods['handling_result']],
                    'time3' => ['value' => $goods['time']],

                ]
            ];
        }
        if (!empty($user)) {
            SELF::pushMsg(
                $user['openid'],
                $msgContent
            );
        }
        if (!empty($seller)) {
            SELF::pushMsg(
                $seller['openid'],
                $msgContent
            );
        } else {
            if (in_array($type, [1, 2], true)) {
                SELF::pushMsg(
                    'oUvn66AAlfD_OFBYeh0E2N3KG6iU',
                    $msgContent
                );
            }
        }
    }

    private static function getAccessToken()
    {
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . __('wechat.gz.appId') . "&secret=" . __('wechat.gz.secret');
        $info = file_get_contents($url);
        $json = json_decode($info);
        $arr = get_object_vars($json);
        return $arr['access_token'];
        /*  if (!Redis::exists('wechat_token')) {
              $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . __('wechat.gz.appId') . "&secret=" . __('wechat.gz.secret');
              $info = file_get_contents($url);
              $json = json_decode($info);
              $arr = get_object_vars($json);
              Redis::setex('wechat_token', 7200, $arr['access_token']);
          }
          return Redis::get('wechat_token');*/
    }

    static private function pushMsg($openId, $msgContent)
    {
        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . SELF::getAccessToken();
        $data = array_merge(['touser' => $openId], $msgContent);
        $result = SELF::httpPostData($url, $data);
        Log::debug('拍卖:' . var_export($result, true));
        return true;
    }

    public static function getMiniAccessToken()
    {
        if (!Redis::exists('mini_token')) {
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . __('wechat.gz.appId') . "&secret=" . __('wechat.gz.secret');
            $info = file_get_contents($url);
            $json = json_decode($info);
            $arr = get_object_vars($json);
            Redis::setex('mini_token', 7200, $arr['access_token']);
        }
        return Redis::get('mini_token');
    }

    //获取授权账号的authorizer_access_token
    public static function getComponentAccessToken()
    {
        if (!Redis::exists('com_token')) {
            $url = "https://api.weixin.qq.com/cgi-bin/component/api_component_token";
            $wxData = [
                'component_appid' => 'wx762e7f3b4c38adf5',
                'component_appsecret' => 'wx7566e1da1a3c5d0a',
                'component_verify_ticket' => ''
            ];
            $json = json_decode($wxData);
            self::httpPostData($url, $wxData);
            $arr = get_object_vars($json);
            Redis::setex('com_token', 7200, $arr['authorizer_access_token']);
        }
        return Redis::get('com_token');
    }

    public static function miNiDelivery($data)
    {
        $url = sprintf(__('wechat.hwmini.delivery_url'), self::getMiniAccessToken());
        $result = SELF::httpPostData($url, $data);
        return $result;
        Log::debug('小程序发货:' . var_export($result, true));
        return true;
    }

    public static function httpPostData($url, $data)
    {
        $data = json_encode($data);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json; charset=utf-8',
            'Content-Length: ' . strlen($data)
        ));
        $returnContent = curl_exec($ch);
        return $returnContent;
    }
}
